import { Reducer } from 'redux';
import qs from 'qs';
import { message } from 'antd';
import { checkToken } from '@/services/kanbanServices';
import { getImgServiceByCode } from '@/services/modelManageService';
import { jsapi, viewUtils } from '@/utils/arcgis';

export enum WORKING_TAB {
  'monitoringIntegration',
  'progressRendering',
  'qualityAndSafety',
  'lineCheck',
  'cityModeling',
  'home',
}

export interface AppModelState {
  viewLoaded: boolean;
  isShowProjList: boolean;
  curProjId: string;
  curProjName: string;
  curProj: any;
  isGlobalProcessRender: boolean;
  token: string;
  userName: string;
  basemapIndex: number;
  isFullScreen: boolean;
  tileLayers: any[];
  curWorkingTab:
    | 'monitoringIntegration'
    | 'progressRendering'
    | 'qualityAndSafety'
    | 'lineCheck'
    | 'cityModeling'
    | 'home';
}

interface dictionary {
  [key: string]: any;
}

export interface AppModelTypes {
  namespace: 'app';
  state: AppModelState;
  effects: {
    // sampleEffectFunc: Effect;
  };
  reducers: {
    updateViewLoaded: Reducer<AppModelState>;
    updateState: Reducer<AppModelState>;
  };
}

function getProjectInfo(): {
  curProjId: string;
  curProjName: string;
  token: string;
  userName: string;
  basemapIndex: number;
} {
  const queryStr = decodeURIComponent(window.location.search);
  let queryObj: dictionary = {};
  try {
    queryObj = qs.parse(queryStr.split('?')[1] || '');
  } catch (error) {
    queryObj = {};
  }
  // sessionStorage.setItem('kanbanToken', queryObj.token || '')
  // @ts-ignore
  window.appcfg.kanbanToken = queryObj.token || '';
  if (process.env.NODE_ENV === 'development') {
    // @ts-ignore
    window.appcfg.kanbanToken = 'ac1a80d836fad59eca9b4d85eebb3dfb';
  }

  if (!queryObj.token) {
    // message.error('没有传入token', 8);
    // todo 暂时使用开发token
    window.appcfg.kanbanToken = 'ac1a80d836fad59eca9b4d85eebb3dfb';
  } else {
    checkToken(queryObj.token).then(data => {
      console.log(data);
      if (!data) {
        // message.error('token不合法', 8);
      }
    });
  }

  // 初始化底图选择
  let basemapIndex: number = 3;
  if (/projectPage/.test(window.location.href)) {
    basemapIndex = 1;
  }
  if (queryObj.token) {
    sessionStorage.setItem('token', queryObj.token);
  }
  if (queryObj.userName) {
    sessionStorage.setItem('userName', queryObj.userName);
  }

  return {
    curProjId: (queryObj.i as string) || '',
    curProjName: (queryObj.n as string) || '',
    token: (queryObj.token as string) || '',
    userName: (queryObj.userName as string) || '',
    basemapIndex: basemapIndex as number,
  };
}

const AppModel: AppModelTypes = {
  namespace: 'app',

  state: {
    viewLoaded: false,
    isShowProjList: false,
    isGlobalProcessRender: false,
    ...getProjectInfo(),
    curProj: null,
    isFullScreen: false,
    tileLayers: [],
    curWorkingTab: 'home',
  },

  effects: {
    *pushUrl({ payload }, { put, select }) {
      console.log('pushUrl被触发了')
      let urlArr = window.location.pathname.split('/');
      urlArr.pop();
      const { token, userName } = yield select(store => store.app);
      let queryObj: any = { token, userName };
      // 默认跳主页
      let url = 'index.html?';

      // 有项目id和项目名称跳项目
      if (payload && payload.i) {
        queryObj.i = payload.i;
        queryObj.n = payload.n;
        url = 'projectPage.html?';
      }

      // 有其他url跳其他url
      if (payload && payload.url) {
        let { url: _url, ..._queryObj } = payload;
        Object.assign(queryObj, _queryObj);
        url = _url + '?';
      }

      url += qs.stringify(queryObj);
      urlArr.push(url);
      window.location.href = urlArr.join('/');
      console.log(urlArr);
    },

    *initTileLayers({ payload }, { put, call, select }) {
      console.log('initTileLayers被触发了')
      const code = yield select(store => store.app.curProjId);
      if (!code) return;
      const resp = yield call(getImgServiceByCode, code);
      console.log(resp);
      if (resp.data.modelList && resp.data.modelList.length) {
        const [TileLayer] = yield jsapi.load(['esri/layers/TileLayer']);
        const view = yield viewUtils.isViewReady();
        let layers: any[] = [];
        let _tileLayers: any[] = [];
        resp.data.modelList
          .filter(e => e.visible)
          .forEach(e => {
            _tileLayers.push({
              url: e.url,
              title: e.name,
            });
            layers.push(
              new TileLayer({
                url: e.url,
                title: e.name,
              }),
            );
          });
        layers.length && view.map.addMany(layers);
        if (_tileLayers.length) {
          yield put({
            type: 'updateState',
            payload: {
              tileLayers: _tileLayers,
            },
          });
        }
      }
    },
  },

  reducers: {
    updateState(state, { payload }): AppModelState {
      return { ...state, ...payload };
    },
    // @ts-ignore
    updateViewLoaded(state = { viewLoaded: true }, { payload }): AppModelState {
      return { ...state, viewLoaded: payload };
    },
  },
};

export default AppModel;
